package org.glorylight.hacks.social.controller;

import java.util.List;
import java.util.UUID;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.glorylight.hacks.social.data.ScrapBookData;
import org.glorylight.hacks.social.data.ScrapBookVotesData;
import org.glorylight.hacks.social.service.ScrapBookService;
import org.glorylight.hacks.social.service.VoteService;
import org.glorylight.hacks.social.util.UUIDHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class VoteController extends AbstractBaseController {

	private static Logger log = LoggerFactory.getLogger(VoteController.class);
	
	@Autowired
	private ScrapBookService scrapBookService;
	
	@Autowired
	private VoteService voteService;
	
	@GET
	@Path("/vote/{scrapId}")
	@Produces(MediaType.APPLICATION_JSON)
	public List<ScrapBookVotesData> addVote(@PathParam("scrapId") String scrapId) {
		UUID scrapUuid = UUIDHelper.stringToUUID(scrapId);
		try {
			voteService.vote(scrapUuid, getActiveLogin());
		} catch (Exception e) {
			log.error("user {} is can not add vote to {}", new Object[]{getActiveLogin(), scrapId});
		}
		ScrapBookData scrapBookData = scrapBookService.find(scrapUuid);
		return scrapBookData.getVoters();
	}
	
	@GET
	@Path("/unvote/{scrapId}")
	@Produces(MediaType.APPLICATION_JSON)
	public List<ScrapBookVotesData> removeVote(@PathParam("scrapId") String scrapId) {
		UUID scrapUuid = UUIDHelper.stringToUUID(scrapId);
		try {
			voteService.unvote(scrapUuid, getActiveLogin());
		} catch (Exception e) {
			log.error("user {} is can not remove vote from {}", new Object[]{getActiveLogin(), scrapId});
		}
		ScrapBookData scrapBookData = scrapBookService.find(scrapUuid);
		return scrapBookData.getVoters();
	}
}
